package btc

import (
	"encoding/hex"
	"encoding/json"
	"errors"
	"io/ioutil"

	"gitee.com/coin-kit/base43"
	"github.com/astaxie/beego/httplib"
)

type ReceivedBody struct {
	Rawhex string `json:"rawhex"`
}

type JsonData_1 struct {
	Addresses []string `json:"addresses"`
}

type JsonData_2 struct {
	ScriptPubKey JsonData_1 `json:"scriptPubKey"`
}

type JsonData_3 struct {
	Vout []JsonData_2 `json:"vout"`
}

type JsonData_4 struct {
	Data JsonData_3 `json:"data"`
}

func CheckBTC(Signed, to string) (bool, error) {
	var jsondata JsonData_4
	url := "https://btc.com/service/tx/decode"

	str2, err := base43.Decode(Signed)
	if err != nil {
		return false, errors.New("解码出错" + err.Error())
	}
	rawtxhex := hex.EncodeToString(str2)

	post := httplib.Post(url)
	body := ReceivedBody{
		Rawhex: rawtxhex,
	}
	post.JSONBody(body)
	resp, err := post.DoRequest()
	if err != nil {
		return false, errors.New("请求解析签名串网页错误")
	}
	input, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return false, errors.New("解析签名串网页错误")
	}

	json.Unmarshal([]byte(input), &jsondata)

	for _, v := range jsondata.Data.Vout {
		if to == v.ScriptPubKey.Addresses[0] {
			return true, nil
		}
	}
	return false, nil
}
